<?	

if (!file_exists('configuration.php')) {
	header('Location: installation');
}

require('bootstrap.php');
require('includes/site_config.php');

require('includes/Template.class.php');
require('includes/TemplateSystem.class.php');

// Goto installation directory if its exists
if (!DEBUG && file_exists('installation')) {
	header('Location: installation');
}

$ts = null;
$template = null;
$tmpl_name = resolve_template_name($config, $_GET);

try {
	$ts = new TemplateSystem();
	$ts->init(null);
	$template = $ts->requestTemplate($tmpl_name);
} 
catch (Exception $e) {
	header('location: ' . error_uri('template-loading-error'));
}	

if ($template != null) {
	
	$req = resolve_request_type($_GET);
	switch ($req) {
		case REQUEST_PAGE: {
			
			$template->request_type = Template::PAGE;
			
			// Set page name as default if GET parameter name is empty
			$name = (isset($_GET['name']) && $_GET['name'] != '') ? $_GET['name'] : $config['site_index'];
			
			// Load page. Returns null if page isn't found.
			$template->page = db_get_page(escape($name));
			
			break;
		}	
		case REQUEST_SEARCH: {
			
			$template->request_type = Template::SEARCH;

			$template->search_query = escape($_GET['query']);
			$template->search_results = db_search_pages($template->search_query);
			
			break;
		}
	}

	// Get menu pages
	$template->menu_pages = db_get_menu_pages();

	// Load template index file
	require($template->getIndexPath());
}

?>